﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using kdTraceQueryReq;
using Base;
using kdTraceQueryRsp;
using IniParser;
using IniParser.Model;
using Newtonsoft.Json;


namespace 查快递的小工具
{
    /// <summary>
    /// 文档: https://open.800best.com/doc/api/63627/63658
    /// </summary>
    public class BestService
    {


        private const string Format = "JSON";
        private const string Url = "http://edi-q9.ns.800best.com/kd/api/process";//对应的地址
        private string PartnerID = "xxxx";
        private string PartnerKey = "xxxxx";

        public BestService()
        {
            var parser = new FileIniDataParser();
            IniData ini = parser.ReadFile("MySecretKey.ini");
            PartnerID = ini["Best"]["partner_iD"];
            PartnerKey = ini["Best"]["partner_key"];
        }

        public async Task GetTrackingInfo(QueryItem query)
        {
            try
            {
                query.BeginQueryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string timestamp = query.BeginQueryTime;


                Client client = new Client(Url, PartnerID, PartnerKey, Format);

                //创建请求对象
                KdTraceQueryReq kdTraceQuery = new KdTraceQueryReq();
                MailNos mailNos = new MailNos();
                List<string> mailNo = new List<string>();
                mailNo.Add(query.TrackingNumber);
                mailNos.mailNo = mailNo;
                kdTraceQuery.mailNos = mailNos;

                //response即为百世的响应
                KdTraceQueryRsp response  = await Task.Run(() =>
                {
                    return client.execute<KdTraceQueryRsp>(kdTraceQuery);
                });

                query.HttpStatus = (int)200;
                query.Response = JsonConvert.SerializeObject(response);
                query.Successful = response.result;
                query.EndQueryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                var info = response.traceLogs.FirstOrDefault();
                if (info == null)
                {
                    throw new Exception("没有物流返回");
                }
                var logs = info.traces.trace;
                if (logs.Count > 0)
                {
                    query.LastProcess = $"[{logs[logs.Count - 1].scanType} {logs[logs.Count - 1].remark}]"  ;
                    query.LastUpdatetime =  logs[logs.Count - 1].acceptTime;
                    query.BeginProcess = $"{logs[0].scanType} {logs[0].remark}"  ;
                    query.BeginUpdatetime = logs[0].acceptTime;
                }
            }
            catch (Exception ex)
            {
                query.EndQueryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                query.ErrMsg = ex.Message;
                query.Successful = false;
            }




        }





    }
}
